package com.objcat.servicesecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.objcat.servicesecurity.entity.po.UserPo;
import com.objcat.servicesecurity.entity.po.UserRolePo;
import com.objcat.servicesecurity.entity.vo.RoleVo;
import com.objcat.servicesecurity.mapper.UserMapper;
import com.objcat.servicesecurity.service.RoleService;
import com.objcat.servicesecurity.service.UserRoleService;
import com.objcat.servicesecurity.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author misheep
 * @since 2020-07-29
 */
@Slf4j
@Service("userServiceImpl")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserPo> implements UserService, UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleService roleService;

    /**
     * 用户数据查询
     * @param userName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        UserDetails userDetails = null;
        //根据userName获取userPo
        QueryWrapper<UserPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);
        UserPo userPo = userMapper.selectOne(queryWrapper);
        if(userPo==null) {
            throw new UsernameNotFoundException("数据库中查无此用户！");
        }
        //根据userPo获取权限
        Collection<GrantedAuthority> authorities = getAuthorities(userPo);
        log.info("---加入的权限：-------------"+authorities.toString());
        //将用户包含权限数据由userDetails返回
        userDetails = new User(userPo.getUserName(), userPo.getUserPassword(),true,true,true,true,authorities);
        return userDetails;
    }

    /**
     * 获取用户角色权限
     * @return
     */
    private Collection<GrantedAuthority> getAuthorities(UserPo userPo){
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
        RoleVo roleVo = roleService.getRole(userPo);
//        authList.add(new SimpleGrantedAuthority("ROLE_"+roleVo.getRoleName()));
        authList.add(new SimpleGrantedAuthority(roleVo.getRoleName()));
        return authList;
    }
}
